import { defineStore } from 'pinia';

import { usePermissionStore } from '@/store';
import type { UserInfo } from '@/types/interface';
import { request } from '@/utils/request';
import { getPermissionList, getUserInfo } from '@/api/user';

const InitUserInfo: UserInfo = {
    userName: '', // 用户名，用于展示在页面右上角头像处
    nickName: '',
    avatar: '',
    createTime: '',
    roles: [], // 前端权限模型使用 如果使用请配置modules/permission-fe.ts使用
};

export const useUserStore = defineStore('user', {
    state: () => ({
        token: 'main_token', // 默认token不走权限
        tokenHeader: 'Authorization',
        userInfo: { ...InitUserInfo },
    }),
    getters: {
        roles: (state) => {
            return state.userInfo?.roles;
        },
    },
    actions: {
        async login(userInfo: Record<string, unknown>) {
            const response = await request.post({ url: '/admin/user/login', data: userInfo });
            // 将请求到的token存储到 pina
            const { token, tokenName } = response;
            this.token = token;
            this.tokenHeader = tokenName;

            // 登录请求流程
            console.log(`用户信息:`, userInfo);
        },
        async getUserInfo() {
            //获取用户数据信息
            this.userInfo = await getUserInfo();
            //获取用户权限信息
            const permissionStore = usePermissionStore();
            permissionStore.getPermissionList();
        },
        async logout() {
            this.token = '';
            this.userInfo = { ...InitUserInfo };
        },
    },
    persist: {
        afterRestore: () => {
            const permissionStore = usePermissionStore();
            //初始化路由
            permissionStore.initRoutes();
        },
        key: 'user',
        paths: ['token'],
    },
});
